#include "display.h"
#include <TFT_eSPI.h>
#include <math.h>
#include "ArduinoJson.h"

#include "font/ZdyLwFont_20.h"
#include "font/FxLED_32.h"

// #include "images/pangzi/i0.h"
// #include "images/pangzi/i1.h"
// #include "images/pangzi/i2.h"
// #include "images/pangzi/i3.h"
// #include "images/pangzi/i4.h"
// #include "images/pangzi/i5.h"
// #include "images/pangzi/i6.h"
// #include "images/pangzi/i7.h"
// #include "images/pangzi/i8.h"
// #include "images/pangzi/i9.h"

#include "images/shouzi/i0.h"
#include "images/shouzi/i1.h"
#include "images/shouzi/i2.h"
#include "images/shouzi/i3.h"
#include "images/shouzi/i4.h"
#include "images/shouzi/i5.h"
#include "images/shouzi/i6.h"
#include "images/shouzi/i7.h"
#include "images/shouzi/i8.h"
#include "images/shouzi/i9.h"
#include "images/shouzi/i10.h"
#include "images/shouzi/i11.h"
#include "images/shouzi/i12.h"
#include "images/shouzi/i13.h"
#include "images/shouzi/i14.h"
#include "images/shouzi/i15.h"
#include "images/shouzi/i16.h"
#include "images/shouzi/i17.h"
#include "images/shouzi/i18.h"
#include "images/shouzi/i19.h"
#include "images/shouzi/i20.h"
#include "images/shouzi/i21.h"
#include "images/shouzi/i22.h"
#include "images/shouzi/i23.h"

#include "images/temperature.h"
#include "images/humidity.h"
#include "images/watch_top.h"
#include "images/watch_bottom.h"

#include <TJpg_Decoder.h>


/*
TFT pins should be set in path/to/Arduino/libraries/TFT_eSPI/User_Setups/Setup24_ST7789.h
*/
TFT_eSPI tft = TFT_eSPI();
TFT_eSprite clk = TFT_eSprite(&tft);

uint16_t bgColor = 0x0000;

static lv_disp_buf_t disp_buf;
static lv_color_t buf[LV_HOR_RES_MAX * 10];

WiFiUDP Udp;
time_t getNtpTime();
void sendNTPpacket(IPAddress& address);
bool AutoConfig(void);
void SmartConfig(void);

void digitalClockDisplay();
void printDigits(int digits);
String num2str(int digits);

void my_print(lv_log_level_t level, const char* file, uint32_t line, const char* fun, const char* dsc)
{
	Serial.printf("%s@%d %s->%s\r\n", file, line, fun, dsc);
	Serial.flush();
}

bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t *bitmap)
{
  if (y >= tft.height())
    return 0;
  tft.pushImage(x, y, w, h, bitmap);
  // Return 1 to decode next block
  return 1;
}


void my_disp_flush(lv_disp_drv_t* disp, const lv_area_t* area, lv_color_t* color_p)
{
	uint32_t w = (area->x2 - area->x1 + 1);
	uint32_t h = (area->y2 - area->y1 + 1);

	tft.startWrite();
	tft.setAddrWindow(area->x1, area->y1, w, h);
	tft.pushColors(&color_p->full, w * h, true);
	tft.endWrite();

	lv_disp_flush_ready(disp);
}


void Display::init()
{
	ledcSetup(LCD_BL_PWM_CHANNEL, 5000, 8);
	ledcAttachPin(LCD_BL_PIN, LCD_BL_PWM_CHANNEL);

	lv_init();

	lv_log_register_print_cb(my_print); /* register print function for debugging */

	tft.begin(); /* TFT init */
	tft.setRotation(4); /* mirror */

	lv_disp_buf_init(&disp_buf, buf, NULL, LV_HOR_RES_MAX * 10);

	/*Initialize the display*/
	lv_disp_drv_t disp_drv;
	lv_disp_drv_init(&disp_drv);
	disp_drv.hor_res = 240;
	disp_drv.ver_res = 240;
	disp_drv.flush_cb = my_disp_flush;
	disp_drv.buffer = &disp_buf;
	lv_disp_drv_register(&disp_drv);
  
  TJpgDec.setJpgScale(1);
  TJpgDec.setSwapBytes(true);
  TJpgDec.setCallback(tft_output);

  TJpgDec.drawJpg(0, 0, watchtop, sizeof(watchtop));
  TJpgDec.drawJpg(0, 220, watchbottom, sizeof(watchbottom));
}

void Display::routine()
{
	lv_task_handler();
}

void Display::setBackLight(float duty)
{
	duty = constrain(duty, 0, 1);
	duty = 1 - duty;
	ledcWrite(LCD_BL_PWM_CHANNEL, (int)(duty * 255));
}



/*** Vaule statement ***/
boolean isNTPConnected = false;
static const char ntpServerName[] = "ntp1.aliyun.com"; //NTP服务器，阿里云
const int timeZone = 8;                                //时区，北京时间为+8
const int NTP_PACKET_SIZE = 48;     // NTP时间在消息的前48个字节里
byte packetBuffer[NTP_PACKET_SIZE]; // 输入输出包的缓冲区
//显示NTP时间
void Display::ShowTime(bool FlagSerialShow)
{
    int years, months, days, hours, minutes, seconds, weekdays;
    String str;

    if (isNTPConnected)
    {
        // Serial.println("(UTC+8)");
        tft.setTextColor(TFT_GREEN,TFT_BLACK);
        str = "   UTC+8 ";
        tft.drawRightString(str,220, 20, 4);
    }   
    else
    {
        //Serial.println("无网络!"); //如果上次对时失败，则会显示无网络
        tft.setTextColor(TFT_RED,TFT_BLACK);
        str = " Sync X";
        tft.drawRightString(str,220, 20, 4);
    }
        
    years = year();
    months = month();
    days = day();
    hours = hour();
    minutes = minute();
    seconds = second();
    weekdays = weekday();
    
    if (FlagSerialShow)
        Serial.printf("%d/%d/%d %d:%d:%d\n", years, months, days, hours, minutes, seconds, weekdays);


    
    char currentTime[15];
    char currentDay[15];

     sprintf((char *)currentTime,"%02d:%02d:%02d",hours,minutes,seconds);
    //sprintf((char *)currentTime,"%02d:%02d",hours,minutes);
    tft.setTextColor(TFT_WHITE,TFT_BLACK);
    tft.drawCentreString(currentTime,120, 100, 7);


    sprintf((char *)currentDay,"%d/%02d/%02d",years,months,days);
    tft.setTextColor(TFT_WHITE,TFT_BLACK);
    tft.drawString(currentDay,20, 20, 2);
    //Serial.println(currentTime);

}

void Display::SyncTime()
{
    setSyncProvider(getNtpTime);
    setSyncInterval(300); //每300秒同步一次时间
}
time_t getNtpTime()
{
  IPAddress ntpServerIP;          // NTP服务器的地址

  while (Udp.parsePacket() > 0);  // 丢弃以前接收的任何数据包
  Serial.println("Transmit NTP Request");
  // 从池中获取随机服务器
  WiFi.hostByName(ntpServerName, ntpServerIP);
  Serial.print(ntpServerName);
  Serial.print(": ");
  Serial.println(ntpServerIP);
  sendNTPpacket(ntpServerIP);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500)
  {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE)
    {
      Serial.println("Receive NTP Response");
      isNTPConnected = true;
      Udp.read(packetBuffer, NTP_PACKET_SIZE); // 将数据包读取到缓冲区
      unsigned long secsSince1900;
      // 将从位置40开始的四个字节转换为长整型，只取前32位整数部分
      secsSince1900 = (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      Serial.println(secsSince1900);
      Serial.println(secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR);
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-("); //无NTP响应
  isNTPConnected = false;
  return 0; //如果未得到时间则返回0
}

// 向给定地址的时间服务器发送NTP请求
void sendNTPpacket(IPAddress& address)
{
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  packetBuffer[0] = 0b11100011; // LI, Version, Mode
  packetBuffer[1] = 0;          // Stratum, or type of clock
  packetBuffer[2] = 6;          // Polling Interval
  packetBuffer[3] = 0xEC;       // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12] = 49;
  packetBuffer[13] = 0x4E;
  packetBuffer[14] = 49;
  packetBuffer[15] = 52;
  Udp.beginPacket(address, 123); //NTP需要使用的UDP端口号为123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

#define CLOCK_CENTER_X 120
#define CLOCK_CENTER_Y 120
#define CLOCK_UI_MARGIN_TOP 0//40
#define CLOCK_UI_W8_COL 5
#define CLOCK_UI_W8_ROW 4
#define CLOCK_UI_CELL_WIDTH (240 / CLOCK_UI_W8_COL - 2) //65
#define CLOCK_UI_CELL_HEIGHT (240 / CLOCK_UI_W8_ROW - 2) //65

void calculate_point_on_circle(int16_t x0, int16_t y0, float radius, float angle, int* outputX, int* outputY) {
    float x1, y1;
    x1 = x0 + radius * cosf(angle * M_PI / 180);
    y1 = y0 + radius * sinf(angle * M_PI / 180);

    *outputX = roundf(x1);
    *outputY = roundf(y1);

//    Log_info3("angle: %d, x = %d, y = %d", angle, x1, y1);
}


#define UG_CIRF(x,y,r,c) tft.fillCircle(x+24,y,r,TFT_WHITE)
#define UG_PL(x1,y1,x2,y2,c) tft.drawLine(x1+24, y1, x2+24, y2, TFT_WHITE)

void Display::showClock() {

  // UG_CIR(CLOCK_CENTER_X,CLOCK_CENTER_Y,90,15);
  // UG_CIRF(CLOCK_CENTER_X,CLOCK_CENTER_Y, 90, TFT_BLACK);
  // tft.fillCircle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 90, TFT_BLACK);
  tft.drawCircle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 90, TFT_WHITE);
  int x = 0, y = 0;
  int x1 = 0, x2 = 0, y1 = 0, y2 = 0, color = 15, c_r = 0;
  float angle = 0;

  const char text[5] = { 0, 0, 0, 0, 0 };
  for (int i = 0; i <= 330; i += 30) {
    calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 72, i - 90, &x, &y);
    int fx = x - (i >= 10 || i == 0 ? 6 : 3);
    int fy = y - 6;
    sprintf((char *)text,"%d", (i == 0 ? 12 : i / 30));
    // UG_DS16(x - (i >= 10 || i == 0 ? 6 : 3), y - 6, "%d", 15, (i == 0 ? 12 : i / 30));

    tft.setTextColor(TFT_WHITE,TFT_BLACK);
    tft.drawString(text, fx, fy, 2);

    calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 90, i - 90, &x, &y);
    calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 83, i - 90, &x1, &y1);
    tft.drawLine(x, y, x1, y1, TFT_WHITE);
  }

  UG_CIRF(183,129,1,15);UG_CIRF(9,111,1,15);UG_CIRF(181,138,1,15);UG_CIRF(11,102,1,15);UG_CIRF(179,147,1,15);UG_CIRF(13,93,1,15);UG_CIRF(175,155,1,15);UG_CIRF(17,85,1,15);UG_CIRF(166,171,1,15);UG_CIRF(26,69,1,15);UG_CIRF(161,178,1,15);UG_CIRF(31,62,1,15);UG_CIRF(154,185,1,15);UG_CIRF(38,55,1,15);UG_CIRF(147,190,1,15);UG_CIRF(45,50,1,15);UG_CIRF(131,199,1,15);UG_CIRF(61,41,1,15);UG_CIRF(123,203,1,15);UG_CIRF(69,37,1,15);UG_CIRF(114,205,1,15);UG_CIRF(78,35,1,15);UG_CIRF(105,207,1,15);UG_CIRF(87,33,1,15);UG_CIRF(87,207,1,15);UG_CIRF(105,33,1,15);UG_CIRF(78,205,1,15);UG_CIRF(114,35,1,15);UG_CIRF(69,203,1,15);UG_CIRF(123,37,1,15);UG_CIRF(61,199,1,15);UG_CIRF(131,41,1,15);UG_CIRF(45,190,1,15);UG_CIRF(147,50,1,15);UG_CIRF(38,185,1,15);UG_CIRF(154,55,1,15);UG_CIRF(31,178,1,15);UG_CIRF(161,62,1,15);UG_CIRF(26,171,1,15);UG_CIRF(166,69,1,15);UG_CIRF(17,155,1,15);UG_CIRF(175,85,1,15);UG_CIRF(13,147,1,15);UG_CIRF(179,93,1,15);UG_CIRF(11,138,1,15);UG_CIRF(181,102,1,15);UG_CIRF(9,129,1,15);UG_CIRF(183,111,1,15);

  // UG_PL(174,165,18,75,15);UG_PL(141,198,51,42,15);UG_PL(51,198,141,42,15);UG_PL(18,165,174,75,15);
  // tft.fillCircle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 59, TFT_BLACK);


  tft.fillCircle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 59, TFT_BLACK);
  // years = year();
  // months = month();
  // days = day();
  int hours = hour();
  int minutes = minute();
  int seconds = second();
  angle = ((float)(hours >= 12 ? hours - 12 : hours) / 12.0 * 360.0 + ((minutes) / 60.0 * 30.0) + ((seconds) / 60.0 * 6.0) - 90);

  c_r = 8;
  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 42, angle, &x, &y);

  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, angle - 90, &x1, &y1);
  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, angle + 90, &x2, &y2);
  tft.fillTriangle(x1,y1,x2,y2,x,y,TFT_RED);
  tft.fillCircle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, TFT_RED);


  angle = ((float)(minutes) / 60.0 * 360.0 + ((seconds) / 60.0 * 6.0) - 90);
  color = 5;
  c_r = 6;
  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 52, angle, &x, &y);
  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, angle - 90, &x1, &y1);
  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, angle + 90, &x2, &y2);
  tft.fillTriangle(x1,y1,x2,y2,x,y,TFT_CYAN);
  tft.fillCircle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, TFT_CYAN);

  angle = ((float)(seconds) / 60.0 * 360.0 - 90);
  color = 1;
  c_r = 3;
  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, 58, angle, &x, &y);
  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, angle - 90, &x1, &y1);
  calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, angle + 90, &x2, &y2);
  // UG_PL(CLOCK_CENTER_X, CLOCK_CENTER_Y,x,y, color);
  // tft.drawLine(CLOCK_CENTER_X, CLOCK_CENTER_Y, x, y, TFT_YELLOW);
  tft.fillTriangle(x1,y1,x2,y2,x,y,TFT_YELLOW);
  tft.fillCircle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r, TFT_YELLOW);
  
  // for (int i = 1; i <= c_r; i++) {
  //   calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r - i, angle - 90, &x1, &y1);
  //   calculate_point_on_circle(CLOCK_CENTER_X, CLOCK_CENTER_Y, c_r - i, angle + 90, &x2, &y2);
  //   UG_PL(x1, y1, x, y, color);
  //   UG_PL(x2, y2, x, y, color);
  // }
  // UG_CIRF(CLOCK_CENTER_X,CLOCK_CENTER_Y,c_r,color);
  
}

//wifi连接
int Display::PreWIFIConnect(String ssid, String pass)
{
    String str;
    
    tft.setTextColor(TFT_WHITE);
    str = "Waiting for WiFi";   tft.drawString(str,10, 10, 2);
    str = "connection...";      tft.drawString(str,10, 30, 2);

	
    wifi.init(ssid.c_str(), pass.c_str());
    uint8_t t=0;
    while (WiFi.status() != WL_CONNECTED)
	{
		
        delay(500);
		Serial.print(".");
        
        if(t == 75)
        {
            tft.setTextColor(TFT_RED);
            str = "WiFi connected ERR ";
            tft.drawString(str,0,50,4);
            //tft.setCursor(10, 50, 4);tft.println(str); 
            
        }

        if(t == 150)
        {
            str = "Reset in 5s later.. ";
            tft.drawString(str,0,70,4);
            
            t=0;

            ESP.restart();
        }

        t++; 
	}

    tft.setTextColor(TFT_GREEN);
    str = "WiFi connected OK  ";
    tft.drawString(str,0,50,4);

    tft.setTextColor(TFT_WHITE);
	  str = "IP address: ";
    tft.drawString(str,10, 70, 2);
    str = WiFi.localIP().toString().c_str();
    tft.drawString(str,120, 70, 2);
    
    str = "MAC address: ";
    tft.drawString(str,10, 90, 2);
    str = WiFi.macAddress().c_str();
    tft.drawString(str,120, 90, 2);
    
    setSyncProvider(getNtpTime);
    setSyncInterval(300); //每300秒同步一次时间

    return 0;

}
//web连接
int Display::PreWebConnect(String WIFI_Name)
{ 
    if (!AutoConfig())
    {
        SmartConfig();
        esp_restart();
    }  
    return 0;

}


String scrollText[6];
//int scrollTextWidth = 0;
//天气信息写到屏幕上
void weaterData(String *cityDZ, String *dataSK, String *dataFC)
{

  DynamicJsonDocument doc(512);
  deserializeJson(doc, *dataSK);
  JsonObject sk = doc.as<JsonObject>();

  //TFT_eSprite clkb = TFT_eSprite(&tft);

  /***绘制相关文字***/
  clk.setColorDepth(8);
  clk.loadFont(ZdyLwFont_20);

  //温度
  clk.createSprite(54, 32);
  clk.fillSprite(bgColor);
  clk.setTextDatum(CC_DATUM);
  clk.setTextColor(TFT_WHITE, bgColor);
  clk.drawString(sk["temp"].as<String>() + "℃", 27, 16);
  clk.pushSprite(185, 168);
  clk.deleteSprite();

  //城市名称
  clk.createSprite(88, 32);
  clk.fillSprite(bgColor);
  clk.setTextDatum(CC_DATUM);
  clk.setTextColor(TFT_WHITE, bgColor);
  clk.drawString(sk["cityname"].as<String>(), 44, 16);
  clk.pushSprite(151, 1);
  clk.deleteSprite();

  //PM2.5空气指数
  uint16_t pm25BgColor = tft.color565(156, 202, 127); //优
  String aqiTxt = "优";
  int pm25V = sk["aqi"];
  if (pm25V > 200)
  {
    pm25BgColor = tft.color565(136, 11, 32); //重度
    aqiTxt = "重度";
  }
  else if (pm25V > 150)
  {
    pm25BgColor = tft.color565(186, 55, 121); //中度
    aqiTxt = "中度";
  }
  else if (pm25V > 100)
  {
    pm25BgColor = tft.color565(242, 159, 57); //轻
    aqiTxt = "轻度";
  }
  else if (pm25V > 50)
  {
    pm25BgColor = tft.color565(247, 219, 100); //良
    aqiTxt = "良";
  }
  clk.createSprite(50, 24);
  clk.fillSprite(bgColor);
  clk.fillRoundRect(0, 0, 50, 24, 4, pm25BgColor);
  clk.setTextDatum(CC_DATUM);
  clk.setTextColor(0x0000);
  clk.drawString(aqiTxt, 25, 13);
  clk.pushSprite(5, 130);
  clk.deleteSprite();

  //湿度
  clk.createSprite(56, 24);
  clk.fillSprite(bgColor);
  clk.setTextDatum(CC_DATUM);
  clk.setTextColor(TFT_WHITE, bgColor);
  clk.drawString(sk["SD"].as<String>(), 28, 13);
  //clk.drawString("100%",28,13);
  clk.pushSprite(180, 130);
  clk.deleteSprite();

  scrollText[0] = "实时天气 " + sk["weather"].as<String>();
  scrollText[1] = "空气质量 " + aqiTxt;
  scrollText[2] = "风向 " + sk["WD"].as<String>() + sk["WS"].as<String>();

  //左上角滚动字幕
  //解析第二段JSON
  deserializeJson(doc, *cityDZ);
  JsonObject dz = doc.as<JsonObject>();
  //Serial.println(sk["ws"].as<String>());
  //横向滚动方式
  //String aa = "今日天气:" + dz["weather"].as<String>() + "，温度:最低" + dz["tempn"].as<String>() + "，最高" + dz["temp"].as<String>() + " 空气质量:" + aqiTxt + "，风向:" + dz["wd"].as<String>() + dz["ws"].as<String>();
  //scrollTextWidth = clk.textWidth(scrollText);
  //Serial.println(aa);
  scrollText[3] = "今日" + dz["weather"].as<String>();

  deserializeJson(doc, *dataFC);
  JsonObject fc = doc.as<JsonObject>();

  scrollText[4] = "最低温度" + fc["fd"].as<String>() + "℃";
  scrollText[5] = "最高温度" + fc["fc"].as<String>() + "℃";

  //Serial.println(scrollText[0]);

  clk.unloadFont();
}

int currentIndex = 0;
int prevTime = 0;
TFT_eSprite clkb = TFT_eSprite(&tft);


time_t prevDisplay = 0; // 显示时间
unsigned long weaterTime = 0;

void scrollTxt(int pos)
{
  clkb.createSprite(148, 24);
  clkb.fillSprite(bgColor);
  clkb.setTextWrap(false);
  clkb.setTextDatum(CC_DATUM);
  clkb.setTextColor(TFT_WHITE, bgColor);
  clkb.drawString(scrollText[currentIndex], 74, pos + 12);
  clkb.pushSprite(2, 4);
}

void scrollBanner()
{
  if (millis() - prevTime > 2500)
  { //2.5秒切换一次

    if (scrollText[currentIndex])
    {

      clkb.setColorDepth(8);
      clkb.loadFont(ZdyLwFont_20);

      for (int pos = 24; pos > 0; pos--)
      {
        scrollTxt(pos);
      }

      clkb.deleteSprite();
      clkb.unloadFont();

      if (currentIndex >= 5)
      {
        currentIndex = 0; //回第一个
      }
      else
      {
        currentIndex += 1; //准备切换到下一个
      }
      //Serial.println(currentIndex);
    }
    prevTime = millis();
  }
}


void imgAnim()
{
  int x = 80, y = 94, dt = 30; //瘦子版dt=10毫秒 胖子30较为合适

  TJpgDec.drawJpg(x, y, i0, sizeof(i0));
  delay(dt);
  TJpgDec.drawJpg(x, y, i1, sizeof(i1));
  delay(dt);
  TJpgDec.drawJpg(x, y, i2, sizeof(i2));
  delay(dt);
  TJpgDec.drawJpg(x, y, i3, sizeof(i3));
  delay(dt);
  TJpgDec.drawJpg(x, y, i4, sizeof(i4));
  delay(dt);
  TJpgDec.drawJpg(x, y, i5, sizeof(i5));
  delay(dt);
  TJpgDec.drawJpg(x, y, i6, sizeof(i6));
  delay(dt);
  TJpgDec.drawJpg(x, y, i7, sizeof(i7));
  delay(dt);
  TJpgDec.drawJpg(x, y, i8, sizeof(i8));
  delay(dt);
  TJpgDec.drawJpg(x, y, i9, sizeof(i9));
  delay(dt);
  TJpgDec.drawJpg(x, y, i10, sizeof(i10));
  delay(dt);
  TJpgDec.drawJpg(x, y, i11, sizeof(i11));
  delay(dt);
  TJpgDec.drawJpg(x, y, i12, sizeof(i12));
  delay(dt);
  TJpgDec.drawJpg(x, y, i13, sizeof(i13));
  delay(dt);
  TJpgDec.drawJpg(x, y, i14, sizeof(i14));
  delay(dt);
  TJpgDec.drawJpg(x, y, i15, sizeof(i15));
  delay(dt);
  TJpgDec.drawJpg(x, y, i16, sizeof(i16));
  delay(dt);
  TJpgDec.drawJpg(x, y, i17, sizeof(i17));
  delay(dt);
  TJpgDec.drawJpg(x, y, i18, sizeof(i18));
  delay(dt);
  TJpgDec.drawJpg(x, y, i19, sizeof(i19));
  delay(dt);
  TJpgDec.drawJpg(x, y, i20, sizeof(i20));
  delay(dt);
  TJpgDec.drawJpg(x, y, i21, sizeof(i21));
  delay(dt);
  TJpgDec.drawJpg(x, y, i22, sizeof(i22));
  delay(dt);
  TJpgDec.drawJpg(x, y, i23, sizeof(i23));
  delay(dt);
}


//星期
String week()
{
  String wk[7] = {"日", "一", "二", "三", "四", "五", "六"};
  String s = "周" + wk[weekday() - 1];
  return s;
}

//月日
String monthDay()
{
  String s = String(month());
  s = s + "月" + day() + "日";
  return s;
}
//时分
String hourMinute()
{
  String s = num2str(hour());
  s = s + ":" + num2str(minute());
  return s;
}

String num2str(int digits)
{
  String s = "";
  if (digits < 10)
    s = s + "0";
  s = s + digits;
  return s;
}

void printDigits(int digits)
{
  Serial.print(":");
  if (digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

// 获取城市天气
void getCityWeater(String cityCode)
{
  String URL = "http://d1.weather.com.cn/weather_index/" + cityCode + ".html?_=" + String(now());
  //创建 HTTPClient 对象
  HTTPClient httpClient;

  httpClient.begin(URL);

  //设置请求头中的User-Agent
  httpClient.setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
  httpClient.addHeader("Referer", "http://www.weather.com.cn/");

  //启动连接并发送HTTP请求
  int httpCode = httpClient.GET();
  Serial.println("正在获取天气数据");
  Serial.println(URL);

  //如果服务器响应OK则从服务器获取响应体信息并通过串口输出
  if (httpCode == HTTP_CODE_OK)
  {

    String str = httpClient.getString();
    int indexStart = str.indexOf("weatherinfo\":");
    int indexEnd = str.indexOf("};var alarmDZ");

    String jsonCityDZ = str.substring(indexStart + 13, indexEnd);
    Serial.println(jsonCityDZ);

    indexStart = str.indexOf("dataSK =");
    indexEnd = str.indexOf(";var dataZS");
    String jsonDataSK = str.substring(indexStart + 8, indexEnd);
    Serial.println(jsonDataSK);

    indexStart = str.indexOf("\"f\":[");
    indexEnd = str.indexOf(",{\"fa");
    String jsonFC = str.substring(indexStart + 5, indexEnd);
    Serial.println(jsonFC);

    weaterData(&jsonCityDZ, &jsonDataSK, &jsonFC);
    Serial.println("获取成功");
  }
  else
  {
    Serial.println("请求城市天气错误：");
    Serial.print(httpCode);
  }

  //关闭ESP8266与服务器连接
  httpClient.end();
}

void Display::digitalClockDisplayInit(String cityCode) { 
  
  prevDisplay = 0; // 显示时间
  weaterTime = 0;

  TJpgDec.drawJpg(0, 0, watchtop, sizeof(watchtop));
  TJpgDec.drawJpg(0, 220, watchbottom, sizeof(watchbottom));
  //绘制一个视口
  tft.setViewport(0, 20, 240, 200);
  tft.fillScreen(0x0000);
  tft.fillRoundRect(0, 0, 240, 200, 5, bgColor); //实心圆角矩形
  //tft.resetViewport();

  //绘制线框
  tft.drawFastHLine(0, 34, 240, TFT_WHITE);

  tft.drawFastVLine(150, 0, 34, TFT_WHITE);

  tft.drawFastHLine(0, 166, 240, TFT_WHITE);

  tft.drawFastVLine(60, 166, 34, TFT_WHITE);
  tft.drawFastVLine(160, 166, 34, TFT_WHITE);

  getCityWeater(cityCode);

  TJpgDec.drawJpg(161, 171, temperature, sizeof(temperature)); //温度图标
  TJpgDec.drawJpg(159, 130, humidity, sizeof(humidity));       //湿度图标

}

void Display::digitalClockDisplay(String cityCode)
{

  if (now() != prevDisplay)
  {
    prevDisplay = now();
    clk.setColorDepth(8);

    /***中间时间区***/
    //时分
    clk.createSprite(140, 48);
    clk.fillSprite(bgColor);
    //clk.loadFont(FxLED_48);
    clk.setTextDatum(CC_DATUM);
    clk.setTextColor(TFT_WHITE, bgColor);
    clk.drawString(hourMinute(), 70, 24, 7); //绘制时和分
    //clk.unloadFont();
    clk.pushSprite(28, 40);
    clk.deleteSprite();

    //秒
    clk.createSprite(40, 32);
    clk.fillSprite(bgColor);

    clk.loadFont(FxLED_32);
    clk.setTextDatum(CC_DATUM);
    clk.setTextColor(TFT_WHITE, bgColor);
    clk.drawString(num2str(second()), 20, 16);

    clk.unloadFont();
    clk.pushSprite(170, 60);
    clk.deleteSprite();
    /***中间时间区***/

    /***底部***/
    clk.loadFont(ZdyLwFont_20);
    clk.createSprite(58, 32);
    clk.fillSprite(bgColor);

    //星期
    clk.setTextDatum(CC_DATUM);
    clk.setTextColor(TFT_WHITE, bgColor);
    clk.drawString(week(), 29, 16);
    clk.pushSprite(1, 168);
    clk.deleteSprite();

    //月日
    clk.createSprite(98, 32);
    clk.fillSprite(bgColor);
    clk.setTextDatum(CC_DATUM);
    clk.setTextColor(TFT_WHITE, bgColor);
    clk.drawString(monthDay(), 49, 16);
    clk.pushSprite(61, 168);
    clk.deleteSprite();

    clk.unloadFont();
    /***底部***/
  }

  if (millis() - weaterTime > 300000)
  { //5分钟更新一次天气
    weaterTime = millis();
    getCityWeater(cityCode);
  }
  
  scrollBanner();
  imgAnim();
}

bool AutoConfig(void)
{
    WiFi.begin();
    //如果觉得时间太长可改
    for (int i = 0; i < 20; i++)
    {
        int wstatus = WiFi.status();
        if (wstatus == WL_CONNECTED)
        {
	        Serial.println("WIFI SmartConfig Success");
	        Serial.printf("SSID:%s", WiFi.SSID().c_str());
	        Serial.printf(", PSW:%s\r\n", WiFi.psk().c_str());
	        Serial.print("LocalIP:");
	        Serial.print(WiFi.localIP());
	        Serial.print(" ,GateIP:");
	        Serial.println(WiFi.gatewayIP());
	        return true;
        }
        else
        {
	        Serial.print("WIFI AutoConfig Waiting......");
	        Serial.println(wstatus);
	        delay(1000);
        }
    }
    Serial.println("WIFI AutoConfig Faild!" );
    return false;
}

void SmartConfig(void)
{
  WiFi.mode(WIFI_STA);
  Serial.println("\r\nWait for Smartconfig...");
  WiFi.beginSmartConfig();
  while (1)
  {
    Serial.print(".");
    delay(500);                   // wait for a second
    if (WiFi.smartConfigDone())
    {
    Serial.println("SmartConfig Success");
    Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
    Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
      break;
    }
  }
}
